﻿package
{
	import flash.events.Event;
	import flash.geom.Point;
	import flash.utils.Dictionary;
	import flash.display.*;
		
	import com.urbansquall.litmus.*;
	
	public class CopyPixelsParticleDemo extends AbstractTest
	{
		protected var m_particles:Dictionary;
		protected var m_speeds:Dictionary;
		protected var m_data : BitmapData;
		protected var m_counter : int;
		protected var m_blitData : BitmapData;
		
		public function CopyPixelsParticleDemo():void
		{
			m_particles = new Dictionary(true);
			m_speeds = new Dictionary();
			m_data = new Main.ParticlePNG().bitmapData;
			
			this.addEventListener( Event.ENTER_FRAME, enterFrameHandler );
			
			m_blitData = new BitmapData( 640, 480, true, 0x000000 );
			var blit : Bitmap = new Bitmap( m_blitData );
			this.addChild( blit );
			this.mouseEnabled = false;
			this.mouseChildren = false;
			
			m_counter = 0;
		}
		
		override public function get title() : String { return "CopyPixels Particle Test"; }
		
		override public function dispose() : void
		{
			super.dispose();
			this.removeEventListener( Event.ENTER_FRAME, enterFrameHandler );

			m_particles = null;
			m_speeds = null;
			m_data = null;
		}
		
		private function createParticle() : void
		{
			var particle:Object= new Object();
			particle.x = 0;
			particle.y = m_counter % this.stage.stageHeight;
			m_particles[ particle ] = particle;
			m_speeds[ particle ] = ((m_counter++) % 5) + 1;
		}
		
		private function enterFrameHandler( a_event : Event ):void
		{
			m_blitData.fillRect( m_blitData.rect, 0 );
			
			for( var i : int = 0; i < Main.PARTICLES_PER_FRAME; i++ )
			{
				createParticle();
			}

			var p : Object;
			for each(p in m_particles)
			{
				p.x += m_speeds[ p ];
				if (p.x > this.stage.stageWidth)
				{
					destroyParticle( p );
				}
				else
				{
					renderParticle( p );
				}
			}
		}
		
		private function renderParticle( a_particle : Object ) : void
		{
			var position : Point = new Point( a_particle.x, a_particle.y );
			m_blitData.copyPixels( m_data, m_data.rect, position, null, null, true );
		}
		
		private function destroyParticle( a_particle : Object ) : void
		{
			delete m_particles[ a_particle ];
			delete m_speeds[ a_particle ];
		}
		
		
	}
}